package io.renren.modules.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.exception.JshException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.QueryUtils;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.dao.*;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.DepotItemService;
import io.renren.modules.erp.vo.AccountVo4InOutList;
import io.renren.modules.erp.vo.DepotItemStockWarningCount;
import io.renren.modules.erp.vo.DepotItemVo4Stock;
import io.renren.modules.sys.service.impl.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("depotItemService")
public class DepotItemServiceImpl extends ServiceImpl<DepotItemMapper, DepotItem> implements DepotItemService {
    private Logger logger = LoggerFactory.getLogger(DepotItemServiceImpl.class);

    private final static String TYPE = "入库";
    private final static String SUM_TYPE = "number";
    private final static String IN = "in";
    private final static String OUT = "out";

    @Autowired
    private DepotItemMapper depotItemMapper;
    @Autowired
    private DepotItemMapperEx depotItemMapperEx;
    @Autowired
    private MaterialServiceImpl materialService;
    @Autowired
    private MaterialExtendServiceImpl materialExtendService;
    @Autowired
    SerialNumberMapperEx serialNumberMapperEx;
    @Autowired
    private DepotHeadMapper depotHeadMapper;
    @Autowired
    SerialNumberServiceImpl serialNumberService;
    @Autowired
    private SystemConfigServiceImpl systemConfigService;
    @Autowired
    private MaterialCurrentStockMapper materialCurrentStockMapper;
//    @Autowired
//    private LogService logService;

    public DepotItem getDepotItem(long id)throws Exception {
        DepotItem result=null;
        try{
            result=depotItemMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<DepotItem> getDepotItem()throws Exception {
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotItem> list=null;
        try{
            list=depotItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public PageUtils select(String name, Integer type, String remark, int currPage , int pageSize)throws Exception {
        List<DepotItem> list=null;
        Page<DepotItem> page = new Page<>(currPage,pageSize);

        try{
            list=depotItemMapperEx.selectByConditionDepotItem(name, type, remark,page);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    public Long countDepotItem(String name, Integer type, String remark) throws Exception{
        Long result =null;
        try{
            result=depotItemMapperEx.countsByDepotItem(name, type, remark);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotItem(String beanJson, HttpServletRequest request)throws Exception {
        DepotItem depotItem = JSONObject.parseObject(beanJson, DepotItem.class);
        int result =0;
        try{
            result=depotItemMapper.insertSelective(depotItem);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotItem(String beanJson, Long id, HttpServletRequest request)throws Exception {
        DepotItem depotItem = JSONObject.parseObject(beanJson, DepotItem.class);
        depotItem.setId(id);
        int result =0;
        try{
            result=depotItemMapper.updateByPrimaryKeySelective(depotItem);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDepotItem(Long id, HttpServletRequest request)throws Exception {
        int result =0;
        try{
            result=depotItemMapper.deleteByPrimaryKey(id);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotItem(String ids, HttpServletRequest request)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andIdIn(idList);
        int result =0;
        try{
            result=depotItemMapper.deleteByExample(example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotItem> list =null;
        try{
            list=depotItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public PageUtils findDetailByTypeAndMaterialIdList(Map<String, String> map, Integer currPage, Integer pageSize)throws Exception {
        String mIdStr = map.get("mId");
        Long mId = null;
        if(!StringUtil.isEmpty(mIdStr)) {
            mId = Long.parseLong(mIdStr);
        }
        List<DepotItemVo4DetailByTypeAndMId> list =null;
        Page<DepotItemVo4DetailByTypeAndMId> page =new Page(currPage,pageSize);
        Page<JSONObject> page1 =new Page(currPage,pageSize);

        try{
            list = depotItemMapperEx.findDetailByTypeAndMaterialIdList(mId,page);
            List<JSONObject> dataList =new ArrayList<>();
            if (list != null) {
                for (DepotItemVo4DetailByTypeAndMId d: list) {
                    JSONObject item = new JSONObject();
                    item.put("Number", d.getNumber()); //商品编号
                    String type = d.getType();
                    String subType = d.getSubType();
                    if(("其它").equals(type)) {
                        item.put("Type", subType); //进出类型
                    } else {
                        item.put("Type", subType + type); //进出类型
                    }
                    item.put("BasicNumber", d.getBnum()); //数量
                    item.put("OperTime", d.getOtime().getTime()); //时间
                    dataList.add(item);
                }
            }
            page1.setRecords(dataList);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return new PageUtils(page1);
    }

    public Long findDetailByTypeAndMaterialIdCounts(Map<String, String> map)throws Exception {
        String mIdStr = map.get("mId");
        Long mId = null;
        if(!StringUtil.isEmpty(mIdStr)) {
            mId = Long.parseLong(mIdStr);
        }
        Long result =null;
        try{
            result = depotItemMapperEx.findDetailByTypeAndMaterialIdCounts(mId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotItemWithObj(DepotItem depotItem)throws Exception {
        int result =0;
        try{
            result = depotItemMapper.insertSelective(depotItem);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

   //调拨单
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertTransferDepotItemWithObj(DepotItem depotItem)throws Exception {
        int result =0;
        try{
            result = depotItemMapper.insertTransferSelective(depotItem);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }


    //形态转换单
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertModalShiftDepotItemWithObj(DepotItem depotItem)throws Exception {
        int result =0;
        try{
            result = depotItemMapper.insertModalShiftDepotItemWithObj(depotItem);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }


    //盘点单
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertCheckDepotItemWithObj(DepotItem depotItem)throws Exception {
        int result =0;
        try{
            result = depotItemMapper.insertCheckDepotItemWithObj(depotItem);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotItemWithObj(DepotItem depotItem)throws Exception {
        int result =0;
        try{
            result = depotItemMapper.updateByPrimaryKeySelective(depotItem);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public List<DepotItem> getListByHeaderId(Long headerId)throws Exception {
        List<DepotItem> list =null;
        try{
            DepotItemExample example = new DepotItemExample();
            example.createCriteria().andHeaderIdEqualTo(headerId);
            list = depotItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<DepotItemVo4WithInfoEx> getDetailList(Long headerId)throws Exception {
        List<DepotItemVo4WithInfoEx> list =null;
        try{
            list = depotItemMapperEx.getDetailList(headerId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }


    public List<DepotItemVo4WithInfoEx> findByAll2(String name, String model, String endTime, Integer currPage, Integer pageSize,String depotId)throws Exception {
        List<DepotItemVo4WithInfoEx> list =null;
        Page<DepotItemVo4WithInfoEx> page = new Page(currPage,  pageSize);
        try{
            list = depotItemMapperEx.findByAll2(name, model, endTime, page,depotId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<DepotItemVo4WithInfoEx> findByAll(String name, String model, String endTime, Integer currPage, Integer pageSize)throws Exception {
        List<DepotItemVo4WithInfoEx> list =null;
        Page<DepotItemVo4WithInfoEx> page = new Page(currPage,  pageSize);
        try{
            list = depotItemMapperEx.findByAll(name, model, endTime, page);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }


    public int findByAllCount(String name, String model, String endTime)throws Exception {
        int result=0;
        try{
            result = depotItemMapperEx.findByAllCount(name, model, endTime);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public BigDecimal buyOrSale(String type, String subType, Long MId, String MonthTime, String sumType) throws Exception{
        BigDecimal result= BigDecimal.ZERO;
        try{
            if (SUM_TYPE.equals(sumType)) {
                result= depotItemMapperEx.buyOrSaleNumber(type, subType, MId, MonthTime, sumType);
            } else {
                result= depotItemMapperEx.buyOrSalePrice(type, subType, MId, MonthTime, sumType);
            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;

    }

    /**
     * 统计采购或销售的总金额
     * @param type
     * @param subType
     * @param MonthTime
     * @return
     * @throws Exception
     */
    public BigDecimal inOrOutPrice(String type, String subType, String MonthTime) throws Exception{
        BigDecimal result= BigDecimal.ZERO;
        try{
            result = depotItemMapperEx.inOrOutPrice(type, subType, MonthTime);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveDetials(String rows, Long headerId, Long tenantId, HttpServletRequest request,Long userId) throws Exception{
        //查询单据主表信息
        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);

        //首先回收序列号，如果是调拨，不用处理序列号
        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
            &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
            List<DepotItem> depotItemList = getListByHeaderId(headerId);
            for(DepotItem depotItem : depotItemList){
                Material material= materialService.getMaterial(depotItem.getMaterialId());
                if(material==null){
                    continue;
                }
                if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())){
                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(),depotItem.getHeaderId(),
                            (depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(), userId);
                }
            }
        }
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        if (null != rowArr) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                Long materialExtendId = rowObj.getLong("MaterialExtendId");
                Long materialId = materialExtendService.getMaterialExtend(materialExtendId).getMaterialId();
                depotItem.setMaterialId(materialId);
                depotItem.setMaterialExtendId(rowObj.getLong("MaterialExtendId"));
                depotItem.setMaterialUnit(rowObj.getString("Unit"));

                if (StringUtil.isExist(rowObj.get("OperNumber"))) {
                    depotItem.setOperNumber(rowObj.getBigDecimal("OperNumber"));
                    try {
                        String Unit = rowObj.get("Unit").toString();
                        BigDecimal oNumber = rowObj.getBigDecimal("OperNumber");
                        //以下进行单位换算
                        String unitName = materialService.findUnitName(materialId); //查询计量单位名称
                        if (!StringUtil.isEmpty(unitName)) {
                            String unitList = unitName.substring(0, unitName.indexOf("("));
                            String ratioList = unitName.substring(unitName.indexOf("("));
                            String basicUnit = unitList.substring(0, unitList.indexOf(",")); //基本单位
                            String otherUnit = unitList.substring(unitList.indexOf(",") + 1); //副单位
                            Integer ratio = Integer.parseInt(ratioList.substring(ratioList.indexOf(":") + 1).replace(")", "")); //比例
                            if (Unit.equals(basicUnit)) { //如果等于基础单位
                                depotItem.setBasicNumber(oNumber); //数量一致
                            } else if (Unit.equals(otherUnit)) { //如果等于副单位
                                depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(ratio)) ); //数量乘以比例
                            }
                        } else {
                            depotItem.setBasicNumber(oNumber); //其他情况
                        }
                    } catch (Exception e) {
                        logger.error(">>>>>>>>>>>>>>>>>>>设置基础数量异常", e);
                    }
                }

                if (StringUtil.isExist(rowObj.get("UnitPrice"))) {
                    depotItem.setUnitPrice(rowObj.getBigDecimal("UnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("TaxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("TaxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("AllPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("AllPrice"));
                }
                depotItem.setRemark(rowObj.getString("Remark"));
                if (rowObj.get("DepotId") != null && !StringUtil.isEmpty(rowObj.get("DepotId").toString())) {
                    depotItem.setDepotId(rowObj.getLong("DepotId"));
                }
                if (rowObj.get("AnotherDepotId") != null && !StringUtil.isEmpty(rowObj.get("AnotherDepotId").toString())) {
                    depotItem.setAnotherDepotId(rowObj.getLong("AnotherDepotId"));
                }
                if (StringUtil.isExist(rowObj.get("TaxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("TaxRate"));
                }
                if (StringUtil.isExist(rowObj.get("TaxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("TaxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("TaxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("TaxLastMoney"));
                }
                if (rowObj.get("MType") != null) {
                    depotItem.setMaterialType(rowObj.getString("MType"));
                }
                if (rowObj.get("Remark") != null) {
                    depotItem.setRemark(rowObj.getString("Remark"));
                }
                //出库时判断库存是否充足
                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
                    if(depotItem==null){
                        continue;
                    }
                    Material material= materialService.getMaterial(depotItem.getMaterialId());
                    if(material==null){
                        continue;
                    }
                    BigDecimal stock = getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId);
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
                    if(systemConfigService.getMinusStockFlag() == false && stock.compareTo(thisBasicNumber)<0){
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG,material==null?"":material.getName()));
                    }
                    //出库时处理序列号
                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
                        System.out.println(material.getEnableSerialNumber());
                        //判断商品是否开启序列号，开启的收回序列号，未开启的跳过
                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
                            //查询单据子表中开启序列号的数据列表
                            serialNumberService.checkAndUpdateSerialNumber(depotItem, userId);
                        }
                    }
                }
                this.insertDepotItemWithObj(depotItem);
                //更新当前库存
                updateCurrentStock(depotItem,tenantId);
            }
        }
    }

//     //调拨单修改
//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void saveTransferItemDetials(String rows, Long headerId, Long tenantId, HttpServletRequest request,Long userId) throws Exception{
//        //查询单据主表信息
//        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);
//
//        //首先回收序列号，如果是调拨，不用处理序列号
//        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
//                &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
//            List<DepotItem> depotItemList = getListByHeaderId(headerId);
//            for(DepotItem depotItem : depotItemList){
//                Material material= materialService.getMaterial(depotItem.getMaterialId());
//                if(material==null){
//                    continue;
//                }
//                if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())){
//                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(),depotItem.getHeaderId(),
//                            (depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(), userId);
//                }
//            }
//        }
//        //删除单据的明细
//        deleteDepotItemHeadId(headerId);
//        JSONArray rowArr = JSONArray.parseArray(rows);
//        if (null != rowArr) {
//            for (int i = 0; i < rowArr.size(); i++) {
//                DepotItem depotItem = new DepotItem();
//                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
//                depotItem.setHeaderId(headerId);
//                Long materialExtendId = rowObj.getLong("MaterialExtendId");
//                Long materialId = materialExtendService.getMaterialExtend(materialExtendId).getMaterialId();
//                depotItem.setMaterialId(materialId);
//                depotItem.setMaterialExtendId(rowObj.getLong("MaterialExtendId"));
//                depotItem.setMaterialUnit(rowObj.getString("Unit"));
//
//                if (StringUtil.isExist(rowObj.get("OperNumber"))) {
//                    depotItem.setOperNumber(rowObj.getBigDecimal("OperNumber"));
//                    try {
//                        String Unit = rowObj.get("Unit").toString();
//                        BigDecimal oNumber = rowObj.getBigDecimal("OperNumber");
//                        //以下进行单位换算
//                        String unitName = materialService.findUnitName(materialId); //查询计量单位名称
//                        if (!StringUtil.isEmpty(unitName)) {
//                            String unitList = unitName.substring(0, unitName.indexOf("("));
//                            String ratioList = unitName.substring(unitName.indexOf("("));
//                            String basicUnit = unitList.substring(0, unitList.indexOf(",")); //基本单位
//                            String otherUnit = unitList.substring(unitList.indexOf(",") + 1); //副单位
//                            Integer ratio = Integer.parseInt(ratioList.substring(ratioList.indexOf(":") + 1).replace(")", "")); //比例
//                            if (Unit.equals(basicUnit)) { //如果等于基础单位
//                                depotItem.setBasicNumber(oNumber); //数量一致
//                            } else if (Unit.equals(otherUnit)) { //如果等于副单位
//                                depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(ratio)) ); //数量乘以比例
//                            }
//                        } else {
//                            depotItem.setBasicNumber(oNumber); //其他情况
//                        }
//                    } catch (Exception e) {
//                        logger.error(">>>>>>>>>>>>>>>>>>>设置基础数量异常", e);
//                    }
//                }
//
//                if (StringUtil.isExist(rowObj.get("UnitPrice"))) {
//                    depotItem.setUnitPrice(rowObj.getBigDecimal("UnitPrice"));
//                }
//                if (StringUtil.isExist(rowObj.get("TaxUnitPrice"))) {
//                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("TaxUnitPrice"));
//                }
//                if (StringUtil.isExist(rowObj.get("AllPrice"))) {
//                    depotItem.setAllPrice(rowObj.getBigDecimal("AllPrice"));
//                }
//                depotItem.setRemark(rowObj.getString("Remark"));
//                if (rowObj.get("DepotId") != null && !StringUtil.isEmpty(rowObj.get("DepotId").toString())) {
//                    depotItem.setDepotId(rowObj.getLong("DepotId"));
//                }
//                if (rowObj.get("AnotherDepotId") != null && !StringUtil.isEmpty(rowObj.get("AnotherDepotId").toString())) {
//                    depotItem.setAnotherDepotId(rowObj.getLong("AnotherDepotId"));
//                }
//                if (StringUtil.isExist(rowObj.get("TaxRate"))) {
//                    depotItem.setTaxRate(rowObj.getBigDecimal("TaxRate"));
//                }
//                if (StringUtil.isExist(rowObj.get("TaxMoney"))) {
//                    depotItem.setTaxMoney(rowObj.getBigDecimal("TaxMoney"));
//                }
//                if (StringUtil.isExist(rowObj.get("TaxLastMoney"))) {
//                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("TaxLastMoney"));
//                }
//                if (rowObj.get("MType") != null) {
//                    depotItem.setMaterialType(rowObj.getString("MType"));
//                }
//                if (rowObj.get("Remark") != null) {
//                    depotItem.setRemark(rowObj.getString("Remark"));
//                }
//                //出库时判断库存是否充足
//                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
//                    if(depotItem==null){
//                        continue;
//                    }
//                    Material material= materialService.getMaterial(depotItem.getMaterialId());
//                    if(material==null){
//                        continue;
//                    }
//                    BigDecimal stock = getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId);
//                    BigDecimal thisBasicNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
//                    if(systemConfigService.getMinusStockFlag() == false && stock.compareTo(thisBasicNumber)<0){
//                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
//                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG,material==null?"":material.getName()));
//                    }
//                    //出库时处理序列号
//                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
//                        System.out.println(material.getEnableSerialNumber());
//                        //判断商品是否开启序列号，开启的收回序列号，未开启的跳过
//                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
//                            //查询单据子表中开启序列号的数据列表
//                            serialNumberService.checkAndUpdateSerialNumber(depotItem, userId);
//                        }
//                    }
//                }
//                this.insertDepotItemWithObj(depotItem);
//                //更新当前库存
//                updateCurrentStock(depotItem,tenantId);
//            }
//        }
//    }



    //调拨单的保存修改
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveTransferDetials(String rows, Long headerId, Long tenantId, HttpServletRequest request,Long userId) throws Exception{
        //查询单据主表信息
        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);

        //首先回收序列号，如果是调拨，不用处理序列号
        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
                &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
            List<DepotItem> depotItemList = getListByHeaderId(headerId);
            for(DepotItem depotItem : depotItemList){
                Material material= materialService.getMaterial(depotItem.getMaterialId());
                if(material==null){
                    continue;
                }
                if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())){
                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(),depotItem.getHeaderId(),
                            (depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(), userId);
                }
            }
        }
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        if (null != rowArr) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                Long materialExtendId = rowObj.getLong("MaterialExtendId");
                Long materialId = materialExtendService.getMaterialExtend(materialExtendId).getMaterialId();
                depotItem.setMaterialId(materialId);
                depotItem.setMaterialExtendId(rowObj.getLong("MaterialExtendId"));
                depotItem.setMaterialUnit(rowObj.getString("Unit"));

                if (StringUtil.isExist(rowObj.get("OperNumber"))) {
                    depotItem.setOperNumber(rowObj.getBigDecimal("OperNumber"));
                    try {
                        String Unit = rowObj.get("Unit").toString();
                        BigDecimal oNumber = rowObj.getBigDecimal("OperNumber");
                        //以下进行单位换算
                        String unitName = materialService.findUnitName(materialId); //查询计量单位名称
                        if (!StringUtil.isEmpty(unitName)) {
                            String unitList = unitName.substring(0, unitName.indexOf("("));
                            String ratioList = unitName.substring(unitName.indexOf("("));
                            String basicUnit = unitList.substring(0, unitList.indexOf(",")); //基本单位
                            String otherUnit = unitList.substring(unitList.indexOf(",") + 1); //副单位
                            Integer ratio = Integer.parseInt(ratioList.substring(ratioList.indexOf(":") + 1).replace(")", "")); //比例
                            if (Unit.equals(basicUnit)) { //如果等于基础单位
                                depotItem.setBasicNumber(oNumber); //数量一致
                            } else if (Unit.equals(otherUnit)) { //如果等于副单位
                                depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(ratio)) ); //数量乘以比例
                            }
                        } else {
                            depotItem.setBasicNumber(oNumber); //其他情况
                        }
                    } catch (Exception e) {
                        logger.error(">>>>>>>>>>>>>>>>>>>设置基础数量异常", e);
                    }
                }

                if (StringUtil.isExist(rowObj.get("shiftinDepotName"))) {
                    depotItem.setShiftinDepotName(rowObj.getString("shiftinDepotName"));
                }
                if (StringUtil.isExist(rowObj.get("shiftoutDepotName"))) {
                    depotItem.setShiftoutDepotName(rowObj.getString("shiftoutDepotName"));
                }

                if (StringUtil.isExist(rowObj.get("shiftinDepot"))) {
                    depotItem.setShiftinDepot(rowObj.getLong("shiftinDepot"));
                }
                if (StringUtil.isExist(rowObj.get("shiftoutDepot"))) {
                    depotItem.setShiftoutDepot(rowObj.getLong("shiftoutDepot"));
                }
                if (StringUtil.isExist(rowObj.get("UnitPrice"))) {
                    depotItem.setUnitPrice(rowObj.getBigDecimal("UnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("TaxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("TaxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("AllPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("AllPrice"));
                }
                depotItem.setRemark(rowObj.getString("Remark"));
                if (rowObj.get("DepotId") != null && !StringUtil.isEmpty(rowObj.get("DepotId").toString())) {
                    depotItem.setDepotId(rowObj.getLong("DepotId"));
                }
                if (rowObj.get("AnotherDepotId") != null && !StringUtil.isEmpty(rowObj.get("AnotherDepotId").toString())) {
                    depotItem.setAnotherDepotId(rowObj.getLong("AnotherDepotId"));
                }
                if (StringUtil.isExist(rowObj.get("TaxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("TaxRate"));
                }
                if (StringUtil.isExist(rowObj.get("TaxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("TaxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("TaxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("TaxLastMoney"));
                }
                if (rowObj.get("MType") != null) {
                    depotItem.setMaterialType(rowObj.getString("MType"));
                }
                if (rowObj.get("Remark") != null) {
                    depotItem.setRemark(rowObj.getString("Remark"));
                }
                //出库时判断库存是否充足
                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
                    if(depotItem==null){
                        continue;
                    }
                    Material material= materialService.getMaterial(depotItem.getMaterialId());
                    if(material==null){
                        continue;
                    }
                    BigDecimal stock = getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId);
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
                    if(systemConfigService.getMinusStockFlag() == false && stock.compareTo(thisBasicNumber)<0){
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG,material==null?"":material.getName()));
                    }
                    //出库时处理序列号
                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
                        System.out.println(material.getEnableSerialNumber());
                        //判断商品是否开启序列号，开启的收回序列号，未开启的跳过
                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
                            //查询单据子表中开启序列号的数据列表
                            serialNumberService.checkAndUpdateSerialNumber(depotItem, userId);
                        }
                    }
                }
                this.insertTransferDepotItemWithObj(depotItem);
                //更新当前库存
                updateCurrentStock(depotItem,tenantId);
            }
        }
    }





    //形态转换单的保存修改
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveModalShiftAndDetials(String rows, Long headerId, Long tenantId, HttpServletRequest request,Long userId) throws Exception{
        //查询单据主表信息
        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);

        //首先回收序列号，如果是调拨，不用处理序列号
        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
                &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
            List<DepotItem> depotItemList = getListByHeaderId(headerId);
            for(DepotItem depotItem : depotItemList){
                Material material= materialService.getMaterial(depotItem.getMaterialId());
                if(material==null){
                    continue;
                }
                if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())){
                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(),depotItem.getHeaderId(),
                            (depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(), userId);
                }
            }
        }
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        if (null != rowArr) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                Long materialExtendId = rowObj.getLong("MaterialExtendId");
                Long materialId = materialExtendService.getMaterialExtend(materialExtendId).getMaterialId();
                depotItem.setMaterialId(materialId);
                depotItem.setMaterialExtendId(rowObj.getLong("MaterialExtendId"));
                depotItem.setMaterialUnit(rowObj.getString("Unit"));

                if (StringUtil.isExist(rowObj.get("OperNumber"))) {
                    depotItem.setOperNumber(rowObj.getBigDecimal("OperNumber"));
                    try {
                        String Unit = rowObj.get("Unit").toString();
                        BigDecimal oNumber = rowObj.getBigDecimal("OperNumber");
                        //以下进行单位换算
                        String unitName = materialService.findUnitName(materialId); //查询计量单位名称
                        if (!StringUtil.isEmpty(unitName)) {
                            String unitList = unitName.substring(0, unitName.indexOf("("));
                            String ratioList = unitName.substring(unitName.indexOf("("));
                            String basicUnit = unitList.substring(0, unitList.indexOf(",")); //基本单位
                            String otherUnit = unitList.substring(unitList.indexOf(",") + 1); //副单位
                            Integer ratio = Integer.parseInt(ratioList.substring(ratioList.indexOf(":") + 1).replace(")", "")); //比例
                            if (Unit.equals(basicUnit)) { //如果等于基础单位
                                depotItem.setBasicNumber(oNumber); //数量一致
                            } else if (Unit.equals(otherUnit)) { //如果等于副单位
                                depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(ratio)) ); //数量乘以比例
                            }
                        } else {
                            depotItem.setBasicNumber(oNumber); //其他情况
                        }
                    } catch (Exception e) {
                        logger.error(">>>>>>>>>>>>>>>>>>>设置基础数量异常", e);
                    }
                }

                if (StringUtil.isExist(rowObj.get("otherStatus"))) {
                    depotItem.setOtherStatus(rowObj.getLong("otherStatus"));
                }

                if (StringUtil.isExist(rowObj.get("UnitPrice"))) {
                    depotItem.setUnitPrice(rowObj.getBigDecimal("UnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("TaxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("TaxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("AllPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("AllPrice"));
                }
                depotItem.setRemark(rowObj.getString("Remark"));
                if (rowObj.get("DepotId") != null && !StringUtil.isEmpty(rowObj.get("DepotId").toString())) {
                    depotItem.setDepotId(rowObj.getLong("DepotId"));
                }
                if (rowObj.get("AnotherDepotId") != null && !StringUtil.isEmpty(rowObj.get("AnotherDepotId").toString())) {
                    depotItem.setAnotherDepotId(rowObj.getLong("AnotherDepotId"));
                }
                if (StringUtil.isExist(rowObj.get("TaxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("TaxRate"));
                }
                if (StringUtil.isExist(rowObj.get("TaxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("TaxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("TaxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("TaxLastMoney"));
                }
                if (rowObj.get("MType") != null) {
                    depotItem.setMaterialType(rowObj.getString("MType"));
                }
                if (rowObj.get("Remark") != null) {
                    depotItem.setRemark(rowObj.getString("Remark"));
                }
                //出库时判断库存是否充足
                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
                    if(depotItem==null){
                        continue;
                    }
                    Material material= materialService.getMaterial(depotItem.getMaterialId());
                    if(material==null){
                        continue;
                    }
                    BigDecimal stock = getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId);
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
                    if(systemConfigService.getMinusStockFlag() == false && stock.compareTo(thisBasicNumber)<0){
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG,material==null?"":material.getName()));
                    }
                    //出库时处理序列号
                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
                        System.out.println(material.getEnableSerialNumber());
                        //判断商品是否开启序列号，开启的收回序列号，未开启的跳过
                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
                            //查询单据子表中开启序列号的数据列表
                            serialNumberService.checkAndUpdateSerialNumber(depotItem, userId);
                        }
                    }
                }
                this.insertModalShiftDepotItemWithObj(depotItem);

                //更新当前库存
                updateCurrentStock(depotItem,tenantId);
            }
        }
    }







    //盘点单的保存修改
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveCheckAndDetials(String rows, Long headerId, Long tenantId, HttpServletRequest request,Long userId) throws Exception{
        //查询单据主表信息
        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);

        //首先回收序列号，如果是调拨，不用处理序列号
        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
                &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
            List<DepotItem> depotItemList = getListByHeaderId(headerId);
            for(DepotItem depotItem : depotItemList){
                Material material= materialService.getMaterial(depotItem.getMaterialId());
                if(material==null){
                    continue;
                }
                if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())){
                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(),depotItem.getHeaderId(),
                            (depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(), userId);
                }
            }
        }
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        if (null != rowArr) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                Long materialExtendId = rowObj.getLong("MaterialExtendId");
                Long materialId = materialExtendService.getMaterialExtend(materialExtendId).getMaterialId();
                depotItem.setMaterialId(materialId);
                depotItem.setMaterialExtendId(rowObj.getLong("MaterialExtendId"));
                depotItem.setMaterialUnit(rowObj.getString("Unit"));

                if (StringUtil.isExist(rowObj.get("OperNumber"))) {
                    depotItem.setOperNumber(rowObj.getBigDecimal("OperNumber"));
                    try {
                        String Unit = rowObj.get("Unit").toString();
                        BigDecimal oNumber = rowObj.getBigDecimal("OperNumber");
                        //以下进行单位换算
                        String unitName = materialService.findUnitName(materialId); //查询计量单位名称
                        if (!StringUtil.isEmpty(unitName)) {
                            String unitList = unitName.substring(0, unitName.indexOf("("));
                            String ratioList = unitName.substring(unitName.indexOf("("));
                            String basicUnit = unitList.substring(0, unitList.indexOf(",")); //基本单位
                            String otherUnit = unitList.substring(unitList.indexOf(",") + 1); //副单位
                            Integer ratio = Integer.parseInt(ratioList.substring(ratioList.indexOf(":") + 1).replace(")", "")); //比例
                            if (Unit.equals(basicUnit)) { //如果等于基础单位
                                depotItem.setBasicNumber(oNumber); //数量一致
                            } else if (Unit.equals(otherUnit)) { //如果等于副单位
                                depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(ratio)) ); //数量乘以比例
                            }
                        } else {
                            depotItem.setBasicNumber(oNumber); //其他情况
                        }
                    } catch (Exception e) {
                        logger.error(">>>>>>>>>>>>>>>>>>>设置基础数量异常", e);
                    }
                }

                if (StringUtil.isExist(rowObj.get("realityAmount"))) {
                    depotItem.setRealityAmount(rowObj.getBigDecimal("realityAmount"));
                }
                if (StringUtil.isExist(rowObj.get("berAmount"))) {
                    depotItem.setBerAmount(rowObj.getBigDecimal("berAmount"));
                }

                if (StringUtil.isExist(rowObj.get("UnitPrice"))) {
                    depotItem.setUnitPrice(rowObj.getBigDecimal("UnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("TaxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("TaxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("AllPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("AllPrice"));
                }
                depotItem.setRemark(rowObj.getString("Remark"));
                if (rowObj.get("DepotId") != null && !StringUtil.isEmpty(rowObj.get("DepotId").toString())) {
                    depotItem.setDepotId(rowObj.getLong("DepotId"));
                }
                if (rowObj.get("AnotherDepotId") != null && !StringUtil.isEmpty(rowObj.get("AnotherDepotId").toString())) {
                    depotItem.setAnotherDepotId(rowObj.getLong("AnotherDepotId"));
                }
                if (StringUtil.isExist(rowObj.get("TaxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("TaxRate"));
                }
                if (StringUtil.isExist(rowObj.get("TaxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("TaxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("TaxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("TaxLastMoney"));
                }
                if (rowObj.get("MType") != null) {
                    depotItem.setMaterialType(rowObj.getString("MType"));
                }
                if (rowObj.get("Remark") != null) {
                    depotItem.setRemark(rowObj.getString("Remark"));
                }
                //出库时判断库存是否充足
                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
                    if(depotItem==null){
                        continue;
                    }
                    Material material= materialService.getMaterial(depotItem.getMaterialId());
                    if(material==null){
                        continue;
                    }
                    BigDecimal stock = getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId);
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
                    if(systemConfigService.getMinusStockFlag() == false && stock.compareTo(thisBasicNumber)<0){
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG,material==null?"":material.getName()));
                    }
                    //出库时处理序列号
                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
                        System.out.println(material.getEnableSerialNumber());
                        //判断商品是否开启序列号，开启的收回序列号，未开启的跳过
                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
                            //查询单据子表中开启序列号的数据列表
                            serialNumberService.checkAndUpdateSerialNumber(depotItem, userId);
                        }
                    }
                }
                this.insertCheckDepotItemWithObj(depotItem);

                //更新当前库存
                updateCurrentStock(depotItem,tenantId);
            }
        }
    }





    /**
     * 查询计量单位信息
     *
     * @return
     */
    public String findUnitName(Long mId) throws Exception{
        String unitName = "";
        try {
            unitName = materialService.findUnitName(mId);
            if (unitName != null) {
                unitName = unitName.substring(1, unitName.length() - 1);
                if (unitName.equals("null")) {
                    unitName = "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitName;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDepotItemHeadId(Long headerId)throws Exception {
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andHeaderIdEqualTo(headerId);
        try{
            depotItemMapper.deleteByExample(example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotItemByIds(String ids,Long userId)throws Exception {
        String [] idArray=ids.split(",");
        int  result =0;
        try{
            result =depotItemMapperEx.batchDeleteDepotItemByIds(new Date(),userId,idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public List<DepotItemStockWarningCount> findStockWarningCount(int currPage, Integer pageSize, Integer pid) {

        List<DepotItemStockWarningCount> list = null;
        Page<DepotItemStockWarningCount> page =new Page<>(currPage,pageSize);
        try{
            list =depotItemMapperEx.findStockWarningCount( pid,page);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int findStockWarningCountTotal(Integer pid) {
        int result = 0;
        try{
            result =depotItemMapperEx.findStockWarningCountTotal(pid);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    /**
     * 库存统计
     * @param depotId
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getStockByParam(Long depotId, Long mId, String beginTime, String endTime, Long tenantId){
        //初始库存
        BigDecimal initStock = materialService.getInitStockByMid(depotId, mId);
        //盘点复盘后数量的变动
        BigDecimal stockCheckSum = depotItemMapperEx.getStockCheckSum(depotId, mId, beginTime, endTime);
        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParam(depotId, mId, beginTime, endTime, tenantId);
        BigDecimal intNum = stockObj.getInNum();
        BigDecimal outNum = stockObj.getOutNum();
        return initStock.add(intNum).subtract(outNum).add(stockCheckSum);
    }

    /**
     * 锁库量查询-根据仓库和商品id，锁库量为已审核的销售订单量
     */
    public BigDecimal getLockAmount(Long depotId, Long mId, Long tenantId){

        //盘点复盘后数量的变动
        BigDecimal lockAmount = depotItemMapperEx.getLockAmount(depotId, mId, tenantId);
//        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParam(depotId, mId, beginTime, endTime, tenantId);
//        BigDecimal intNum = stockObj.getInNum();
//        BigDecimal outNum = stockObj.getOutNum();
        return lockAmount;
    }


    /**
     * 入库统计
     * @param depotId
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getInNumByParam(Long depotId, Long mId, String beginTime, String endTime, Long tenantId){
        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParam(depotId, mId, beginTime, endTime, tenantId);
        return stockObj.getInNum();
    }

    /**
     * 出库统计
     * @param depotId
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getOutNumByParam(Long depotId, Long mId, String beginTime, String endTime, Long tenantId){
        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParam(depotId, mId, beginTime, endTime, tenantId);
        return stockObj.getOutNum();
    }

    /**
     * 根据单据明细来批量更新当前库存
     * @param depotItem
     * @param tenantId
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateCurrentStock(DepotItem depotItem, Long tenantId){
        MaterialCurrentStockExample example = new MaterialCurrentStockExample();
        example.createCriteria().andMaterialIdEqualTo(depotItem.getMaterialId()).andDepotIdEqualTo(depotItem.getDepotId())
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<MaterialCurrentStock> list = materialCurrentStockMapper.selectByExample(example);
        MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
        materialCurrentStock.setMaterialId(depotItem.getMaterialId());
        materialCurrentStock.setDepotId(depotItem.getDepotId());
        materialCurrentStock.setCurrentNumber(getStockByParam(depotItem.getDepotId(),depotItem.getMaterialId(),null,null,tenantId));
        if(list!=null && list.size()>0) {
            Long mcsId = list.get(0).getId();
            materialCurrentStock.setId(mcsId);
            materialCurrentStockMapper.updateByPrimaryKeySelective(materialCurrentStock);
        } else {
            materialCurrentStockMapper.insertSelective(materialCurrentStock);
        }
    }
}
